package com.interest.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.interest.authorization.manager.impl.RedisTokenManager;
import com.interest.base.common.Constants;
import com.interest.base.entity.ModelBean;
import com.interest.base.utils.TokenUtils;
import com.interest.modules.account.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登陆控制器
 *
 * @author wangliang
 */
@Controller
@RequestMapping("/api")
public class ApiLoginController {
    @Autowired
    private AccountService accountService;

    @Autowired
    private RedisTokenManager redisTokenManager;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ModelBean login(@RequestParam(value = "username", required = true) String username,
                           @RequestParam(value = "password", required = true) String password) {
        if (username == null || username.length() == 0) {
            return new ModelBean(Constants.STATUS_ERROR, "用户名不能为空");
        } else if (password == null || password.length() == 0) {
            return new ModelBean(Constants.STATUS_ERROR, "密码不能为空");
        } else {
            int uid = accountService.login(username, password);
            if (uid > 0) {
                String token = TokenUtils.generateToken();
                redisTokenManager.createRelationship(username, token);
                JSONObject data = new JSONObject();
                data.put("username", username);
                data.put("token", token);
                return new ModelBean(data);
            } else {
                return new ModelBean(Constants.STATUS_ERROR, "用户名密码错误");
            }
        }
    }


}
